package com.itxiaoz.filter;

import com.itdupan.pojo.Rights;
import com.itxiaoz.client.RightsClient;
import com.itxiaoz.client.RoleRightsClient;
import com.itxiaoz.client.UserClient;
import com.itxiaoz.config.FilterProperties;
import com.itxiaoz.config.JwtProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Teao
 * @CreateTime: 2024-04-17  20:34
 * @Description:
 */
@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})
public class AuthorizationFilter implements GlobalFilter,Ordered {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private FilterProperties filterProperties;

    @Resource
    private RightsClient rightsClient;

    @Resource
    private RoleRightsClient roleRightsClient;

    @Resource
    private UserClient userClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断是否需要过滤
        if (shouldFilter(exchange.getRequest())) {
            // 这里添加您的授权逻辑
            // 如果授权失败，您可以设置响应状态码，例如：
            // exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    private boolean shouldFilter(ServerHttpRequest request) {
        // 查询所有三级菜单的路径
        List<String> paths = new ArrayList<>();
        List<Rights> list = rightsClient.findAll().getData();
        for (Rights r : list) {
            for (Rights r2 : r.getChildren()) {
                for (Rights r3 : r2.getChildren()) {
                    if (r3.getRightsLevel() == 3) {
                        paths.add(r3.getRightsPath());
                    }
                }
            }
        }

        // 获取请求路径
        URI uri = request.getURI();
        String path = uri.getPath();

        // 判断是否需要过滤
        return paths.stream().anyMatch(path::contains);
    }

    public int getOrder() {
        return -100;
    }
}
